package logic;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import data.DBLogin;
import data.HttpClientManager;
import data.HttpClientManager.OnExecuteHttpPostAsyncListener;

import android.app.Activity;


import android.database.Cursor;


public class User {
	 
	 private String Name = "";
	 private String Email = "";
	 private String UID = "";
	 
	    private static String KEY_SUCCESS = "success";
	    private static String KEY_UID = "id_usuario";
	    private static String KEY_NAME = "nombre";
	    private static String KEY_SURNAME = "apellidos";
	    private static String KEY_EMAIL = "mail";
	    private static String KEY_CREATED_AT = "fecha_hora";
	    private static String KEY_USER = "mail";
	    private static String NEW_USER = "newuser";

	 private static String loginURL = "http://unitest.net46.net/index.php/api/login";
	   
	    
	    private Activity activity;
	   
	 

	    public void login(Activity activity, String email, String password){
	     this.activity = activity;
	     HttpClientManager httpclient = new HttpClientManager(activity);
	     httpclient.addNameValue("email", email);
	     httpclient.addNameValue("password", password);
	     
	     if(httpclient.isInternetAllowed(activity)){
	     
	    	 httpclient.setOnExecuteHttpPostAsyncListener(new OnExecuteHttpPostAsyncListener() {
	    	 
				   public void onExecuteHttpPostAsyncListener(String ResponseBody) {
					   //System.out.println(ResponseBody);
					    try {   
					     JSONArray jsonArray = new JSONArray(ResponseBody);	
					     JSONObject json = jsonArray.getJSONObject(0);
					     
						     if (json.getString(KEY_SUCCESS) != null) {
							      if((Integer.parseInt(json.getString(KEY_SUCCESS)) == 1)){   
							    	 
										    	  
								       if(User.this.saveLogin(User.this.activity, json))
								    	   //If user and password corrects
								    	   ListenerLoginUsuario.onLoginCorrect(json, "Login correcto");
								       else 
								    	   //if user exist
								    	   
								    	ListenerLoginUsuario.onUserExistDisplayPassField();
								        ListenerLoginUsuario.onLoginWrong("Your password for log in.");       
							      } else {
							    	  //If user doesn't exist
							    	  //If user and password doesn't match
									    if(Integer.parseInt(json.getString(NEW_USER)) == 1){
									       ListenerLoginUsuario.onLoginWrong("Welcome to Evaluity!");
									       //Safe and jump to main
									       if(User.this.saveLoginNewUser(User.this.activity, json))
									    	   ListenerLoginUsuario.onLoginCorrect(json, "Login correcto");
									       
									       ListenerLoginUsuario.onNewUser();
									       
									       
									    } else {
									    	ListenerLoginUsuario.onLoginWrong("Incorrect password.");
									    }
							       }
						     } else{
						    	 ListenerLoginUsuario.onLoginWrong("Technical problems, try again.");  
						      
						     }     
					    } catch (JSONException e) {
						     ListenerLoginUsuario.onLoginWrong("Login incorrecto");  
						    
						}
				   }
				
					   public void onErrorHttpPostAsyncListener(String message) {
				}   
			});
	    	 
	    	 httpclient.executeHttpPost(loginURL);
	     
	     } else{
	    	 
	    	 //m_ProgressDialog = ProgressDialog.show(activity, "Connection not possible", "Check your connection.", true);
	    	 
	    	 ListenerLoginUsuario.onNotInternetAllowed();
	    	 
	     }
	    	
	     	
	    } 
	    
	 
	 private boolean saveLogin(Activity activity, JSONObject json){
	  boolean save = false;
	  this.logout(activity);
	 
	  try {
	   //JSONObject user = json.getJSONObject(KEY_USER);
	  
	   DBLogin dblogin = new DBLogin(activity);
	   dblogin.addUser(json.getString(KEY_NAME), json.getString(KEY_EMAIL), json.getString(KEY_UID), json.getString(KEY_CREATED_AT));
	   dblogin.close();
	   save = true;   
	  } catch (JSONException e) {}    
	  return save;
	 }
	 
	 private boolean saveLoginNewUser(Activity activity, JSONObject json){
		  boolean save = false;
		  this.logout(activity);
		 
		  try {
		   //JSONObject user = json.getJSONObject(KEY_USER);
		  
		   DBLogin dblogin = new DBLogin(activity);
		   dblogin.addUser("uknown", json.getString(KEY_EMAIL),"-1", "uknown");
		   dblogin.close();
		   save = true;   
		  } catch (JSONException e) {}    
		  return save;
		 }
	 

	 public void logout(Activity activity){
	  DBLogin dblogin = new DBLogin(activity);
	  dblogin.resetTables();
	  dblogin.close();
	 } 
	 

	    public boolean isUserLoggedIn(Activity activity){
	        DBLogin db = new DBLogin(activity);
	        int count = db.getRowCount();
	        db.close();
	        if(count > 0){
	            // user logged in
	            return true;
	        }
	        return false;
	    }
	    
	    public void readUser(Activity activity){
	     DBLogin dblogin = new DBLogin(activity);
	     Cursor cursor = dblogin.getCursorUsuario();
	     if(cursor.moveToNext()){
	      this.setName(cursor.getString(0));
	      this.setEmail(cursor.getString(1));
	      this.setUID(cursor.getString(2));
	     }
	     cursor.close();
	     dblogin.close();
	     
	    }
	 
	 public interface OnRegisterUsuario{
	  void onRegisterFinish(JSONObject json, String msg);
	  void onRegisterException(Exception e, String msg);
	  void onRegisterFail(String msg);
	 } 
	 
	 public interface OnLoginUsuario{
	  void onLoginCorrect(JSONObject json, String msg);
	  void onLoginWrong(String msg);
	  void onUserExistDisplayPassField();
	  void onNewUser();
	  void onNotInternetAllowed();
	 }
	 private OnLoginUsuario ListenerLoginUsuario;
	 public void setOnLoginUsuario(OnLoginUsuario l){ListenerLoginUsuario = l;}

	 public String getName() {return Name;}
	 public void setName(String name) {Name = name;}
	 public String getEmail() {return Email;}
	 public void setEmail(String email) {Email = email;}
	 public String getUID() {return UID;}
	 public void setUID(String uID) {UID = uID;}
	 
	}
